package com.example.nearby;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.Point;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.BounceInterpolator;
import android.view.animation.Interpolator;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.AMap.InfoWindowAdapter;
import com.amap.api.maps2d.AMap.OnInfoWindowClickListener;
import com.amap.api.maps2d.AMap.OnMarkerClickListener;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.Projection;
import com.amap.api.maps2d.model.BitmapDescriptor;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.boyuan.huijiaoyu.R;
import com.example.contactfragment.ContactService;
import com.example.newfragment.HomeService;
import com.magicsoft.app.helper.ToastHelper;
import com.magicsoft.app.wcf.listener.GetOneRecordListener;

public class NearCenterActivity extends Activity implements AMapLocationListener, LocationSource, OnMarkerClickListener, OnClickListener {

	private ContactService contactService;
	ArrayList<NearbyCenter> NearbyCenterList = new ArrayList<NearbyCenter>();
	private LocationManagerProxy mAMapLocationManager;
	private OnLocationChangedListener mListener;
	private double lat;
	private double lng;
	private HomeService homeService;
	// 重新启动应用后 第一次同步（用于是否开始启动计时器）
	private boolean firstSynRunnable = true;
	private MapView mapView;
	private AMap aMap;
	private MarkerOptions markerOption;
	private Marker marker2;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_near_center);
		findViewById(R.id.lay_back1).setOnClickListener(this);
		mapView = (MapView) findViewById(R.id.map);
		mapView.onCreate(savedInstanceState);// 此方法必须重写
		init();
		//定位
		getLocation();

	}
	/**
	 * 初始化
	 */
	private void init() {
		if (aMap == null) {
			aMap = mapView.getMap();
			setUpMap();
		}
	}
	/**
	 * 设置一些amap的属性
	 */
	private void setUpMap() {
		MyLocationStyle myLocationStyle = new MyLocationStyle();
		myLocationStyle.myLocationIcon(BitmapDescriptorFactory
				.fromResource(R.drawable.location_marker));// 设置小蓝点的图标
		aMap.setMyLocationStyle(myLocationStyle);
		aMap.setLocationSource(this);// 设置定位监听
		aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
		aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
		// 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
		//		aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
		aMap.moveCamera(CameraUpdateFactory.zoomTo(12));
		aMap.setOnMarkerClickListener(this);// 设置点击marker事件监听器
//		aMap.setOnInfoWindowClickListener(this);// 设置点击infoWindow事件监听器
//		aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式
	}

	//定位
	private void getLocation() {
		mAMapLocationManager = LocationManagerProxy.getInstance(this);
		mAMapLocationManager.setGpsEnable(false);
		// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
		// 注意设置合适的定位时间的间隔，并且在合适时间调用removeUpdates()方法来取消定位请求
		// 在定位结束后，在合适的生命周期调用destroy()方法
		// 其中如果间隔时间为-1，则定位只定一次
		mAMapLocationManager.requestLocationData(
				LocationProviderProxy.AMapNetwork, -1, 10, this);
	}

	//获取附近中心
	private void getNearByCenter(double lat,double lng) {
		if (contactService == null) {
			contactService = new ContactService(this);
		}
		contactService.getNearByCenterService("0",lat,lng,
				new GetOneRecordListener<List<NearbyCenter>>() {

			@Override
			public void onFinish(List<NearbyCenter> data) {
				NearbyCenterList.clear();
				if (data != null && data.size() > 0) {
					NearbyCenterList.addAll(data);
					for (int i = 0; i < NearbyCenterList.size(); i++) {
						addMarkersToMap(i);
					}
				}

			}

			@Override
			public void onFailed(String Message) {
				ToastHelper.showMsg(NearCenterActivity.this, Message, false);
			}
		});
	}
	@Override
	public void onLocationChanged(Location arg0) {
		// TODO Auto-generated method stub

	}
	@Override
	public void onProviderDisabled(String arg0) {
		// TODO Auto-generated method stub

	}
	@Override
	public void onProviderEnabled(String arg0) {
		// TODO Auto-generated method stub

	}
	@Override
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		// TODO Auto-generated method stub

	}
	@Override
	public void onLocationChanged(AMapLocation aLocation) {

		if (aLocation != null) {
			stopLocation();

			lat = aLocation.getLatitude();
			lng = aLocation.getLongitude();

			if (homeService == null) {
				homeService = new HomeService(this);
			}

			if (lat == 0.0 && lng == 0.0) {
				lat = 39.90960456049752;
				lng = 116.3972282409668;

			}
			String lat_str = String.valueOf(lat);
			String lng_str = String.valueOf(lng);
			//获取附近中心
			getNearByCenter(lat,lng);

			//			homeService.sendUsernameAndRegistrationID(lat_str ,lng_str);
			/**
			 * 定位成功后回调函数
			 */
			if (mListener != null && aLocation != null) {
				if (aLocation != null
						&& aLocation.getAMapException().getErrorCode() == 0) {
					mListener.onLocationChanged(aLocation);// 显示系统小蓝点
				} else {
					Log.e("AmapErr","Location ERR:" + aLocation.getAMapException().getErrorCode());
				}
			}

		}
	}
	private void stopLocation() {

		if (mAMapLocationManager != null) {
			mAMapLocationManager.removeUpdates(this);
			mAMapLocationManager.destroy();
		}
		mAMapLocationManager = null;
	}
	/**
	 * 激活定位
	 */
	@Override
	public void activate(OnLocationChangedListener listener) {
		mListener = listener;
		if (mAMapLocationManager == null) {
			mAMapLocationManager = LocationManagerProxy.getInstance(this);
			// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
			// 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用removeUpdates()方法来取消定位请求
			// 在定位结束后，在合适的生命周期调用destroy()方法
			// 其中如果间隔时间为-1，则定位只定一次
			// 在单次定位情况下，定位无论成功与否，都无需调用removeUpdates()方法移除请求，定位sdk内部会移除

			mAMapLocationManager.requestLocationData(
					LocationProviderProxy.AMapNetwork, 6 * 10, 10, this);
		}		
	}
	/**
	 * 停止定位
	 */
	@Override
	public void deactivate() {
		mListener = null;
		if (mAMapLocationManager != null) {
			mAMapLocationManager.removeUpdates(this);
			mAMapLocationManager.destroy();
		}
		mAMapLocationManager = null;		
	}
	@Override
	public boolean onMarkerClick(Marker marker) {
		//		if (marker.equals(marker2)) {
		if (aMap != null) {
			String title = marker.getTitle();
			//动画效果
			jumpPoint(marker,title);
		}
		//		}
		//		markerText.setText("你点击的是" + marker.getTitle());
		return false;
	}
	private void jumpPoint(final Marker marker,String title) {
		for (int i = 0; i < NearbyCenterList.size(); i++) {
			Log.e("markid====", NearbyCenterList.get(i).getName());
			if(title.equals(NearbyCenterList.get(i).getName())){
				final Handler handler = new Handler();
				final long start = SystemClock.uptimeMillis();
				Projection proj = aMap.getProjection();
				final Double latJump = Double.valueOf(NearbyCenterList.get(i).getLat());
				final Double lngJump = Double.valueOf(NearbyCenterList.get(i).getLng());
				Point startPoint = proj.toScreenLocation(new LatLng(latJump, lngJump));
				startPoint.offset(0, -100);
				final LatLng startLatLng = proj.fromScreenLocation(startPoint);
				final long duration = 1500;

				final Interpolator interpolator = new BounceInterpolator();
				handler.post(new Runnable() {
					@Override
					public void run() {
						long elapsed = SystemClock.uptimeMillis() - start;
						float t = interpolator.getInterpolation((float) elapsed
								/ duration);
						double lng = t * new LatLng(latJump, lngJump).longitude + (1 - t)
								* startLatLng.longitude;
						double lat = t * new LatLng(latJump, lngJump).latitude + (1 - t)
								* startLatLng.latitude;
						marker.setPosition(new LatLng(lat, lng));
						aMap.invalidate();// 刷新地图
						if (t < 1.0) {
							handler.postDelayed(this, 16);
						}
					}
				});
			}
		}

	}
//	@Override
//	public void onInfoWindowClick(Marker arg0) {
//		// TODO Auto-generated method stub
//
//	}
	/**
	 * 方法必须重写
	 */
	@Override
	protected void onResume() {
		super.onResume();
		mapView.onResume();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onPause() {
		super.onPause();
		mapView.onPause();
		deactivate();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mapView.onSaveInstanceState(outState);
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		mapView.onDestroy();
	}
	//获取位置小图标
	private void addMarkersToMap(int i) {
		
			String l1 = NearbyCenterList.get(i).getLat();
			String l2 = NearbyCenterList.get(i).getLng();
			Double lat2 = Double.valueOf(l1);
			Double lng2 = Double.valueOf(l2);
			Marker marker = aMap.addMarker(new MarkerOptions()
			.position(new LatLng(lat2, lng2))
			.title(NearbyCenterList.get(i).getName())
			.icon(BitmapDescriptorFactory
					.fromView(getView(NearbyCenterList.get(i))))
					.draggable(true));
//			marker.showInfoWindow();// 设置默认显示一个infowinfow
			//显示infowinfow
	}
	View getView(NearbyCenter nearbyCenter){
		View inflate = getLayoutInflater().inflate(R.layout.custom_info_window, null);
		TextView title = (TextView) inflate.findViewById(R.id.title);
		title.setText(nearbyCenter.getName());
		return inflate;
		
	}
//	@Override
//	public View getInfoContents(Marker marker) {
//		View infoContent = getLayoutInflater().inflate(
//				R.layout.custom_info_contents, null);
//		for (int i = 0; i < NearbyCenterList.size(); i++) {
//			render(marker, infoContent,i);
//		}
//		
//		return infoContent;
//	}
//	@Override
//	public View getInfoWindow(Marker marker) {
//		View infoWindow = getLayoutInflater().inflate(
//				R.layout.custom_info_window, null);
//		for (int i = 0; i < NearbyCenterList.size(); i++) {
//			
//			render(marker, infoWindow,i);
//		}
//		return infoWindow;
//	}
//	public void render(Marker marker, View view,int i) {
//		
//		String title = marker.getTitle();
//		TextView titleUi = ((TextView) view.findViewById(R.id.title));
//		if (title != null) {
//			SpannableString titleText = new SpannableString(title);
//			titleText.setSpan(new ForegroundColorSpan(Color.RED), 0,
//					titleText.length(), 0);
//			titleUi.setTextSize(15);
//			titleUi.setText(title);
//
//		} else {
//			titleUi.setText(title);
//		}
//		String snippet = marker.getSnippet();
//		TextView snippetUi = ((TextView) view.findViewById(R.id.snippet));
//		if (snippet != null) {
//			SpannableString snippetText = new SpannableString(title);
//			snippetText.setSpan(new ForegroundColorSpan(Color.GREEN), 0,
//					snippetText.length(), 0);
//			snippetUi.setTextSize(20);
//			snippetUi.setText(title);
//		} else {
//			snippetUi.setText(title);
//		}
//	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.lay_back1:
			finish();
			break;

		default:
			break;
		}
	}

}
